<template>
  <!-- 新拆分组件，可以先把内容放在App中，再一点点抽离，剪切内容之后立即使用组件标签替换 -->
  <div>
    <div id="root">
      <div class="todo-container">
        <div class="todo-wrap">
          <!-- 头部输入框-->
          <!-- 父亲可以传输任何数据：字符串、函数、数组、对象，这里给头部子组件传递一个方法 -->
          <AddBehavior :addTodo="addTodo"></AddBehavior>

          <!-- 内容集合 -->
          <!-- 将改动勾选的方法，逐层传递给具体的行为组件（孙子） -->
          <BehaviorList
            :todoList="todoList"
            :checkTodo="checkTodo"
            :deleteTodo="deleteTodo"
          ></BehaviorList>

          <!-- 汇总内容 -->
          <Statistics
            :todoList="todoList"
            :checkAllTodo="checkAllTodo"
            :clearAllTodo="clearAllTodo"
          ></Statistics>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import AddBehavior from "./components/AddBehavior.vue";
import BehaviorList from "./components/BehaviorList.vue";
import Statistics from "./components/Statistics.vue";

export default {
  name: "App",
  components: {
    AddBehavior,
    BehaviorList,
    Statistics,
  },
  data() {
    return {
      //2：初始化从localStorage中取，注意初始化时为空解析后会得到null而不是空数组。 添加或的条件
      todoList: JSON.parse(localStorage.getItem("todoList")) || [],
    };
  },

  methods: {
    addTodo(data) {
      this.todoList.unshift(data);
    },
    checkTodo(todoId) {
      this.todoList.forEach((todo) => {
        if (todo.id === todoId) {
          todo.done = !todo.done;
          console.log("修改成功：" + todo.done);
        }
      });
    },
    deleteTodo(todoId) {
      this.todoList = this.todoList.filter((todo) => {
        return todo.id !== todoId;
      });
    },
    checkAllTodo(isDone) {
      console.log("全选或全不选操作,获取到id:" + isDone);
      this.todoList.forEach((todo) => (todo.done = isDone));
    },
    clearAllTodo() {
      this.todoList = this.todoList.filter((todo) => !todo.done);
    },
  },

  watch: {
    //1：数据发生变化时监听，存到浏览器中
    todoList: {
      //开启深度监视，数组中数据发生改变也触发
      deep: true,
      handler(value) {
        localStorage.setItem("todoList", JSON.stringify(value));
      },
    },
  },
};
</script>

<style>
/*base 基本样式，全局使用*/
body {
  background: #fff;
}

.btn {
  display: inline-block;
  padding: 4px 12px;
  margin-bottom: 0;
  font-size: 14px;
  line-height: 20px;
  text-align: center;
  vertical-align: middle;
  cursor: pointer;
  box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2),
    0 1px 2px rgba(0, 0, 0, 0.05);
  border-radius: 4px;
}

.btn-danger {
  color: #fff;
  background-color: #da4f49;
  border: 1px solid #bd362f;
}

.btn-danger:hover {
  color: #fff;
  background-color: #bd362f;
}

.btn:focus {
  outline: none;
}

.todo-container {
  width: 600px;
  margin: 0 auto;
}

.todo-container .todo-wrap {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
}
</style>